package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.domain.User;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());//自动处理事务
    @Override
    public User selectByUserName(String username) {
        try {
            return queryRunner.query("select*from tb_user where username=? ",new BeanHandler<>(User.class),username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(User user) {
        String sql=" insert into tb_user values (null,?,?,?,?,?,?,?) ";
        Object[] params={ user.getUsername(),user.getPassword(),user.getEmail(),user.getGender(),user.getFlag(),user.getRole(),user.getCode()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int updateFlag(String email, String code) {
        String sql=" update tb_user set flag=1 where email=? and code=? and flag=0 ";
        try {
            return queryRunner.update(sql,email,code);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public List<User> selectAll()  {
        try {
            return queryRunner.query("select * from tb_user",new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(String uid)  {
        try {
            queryRunner.update("delete from tb_user where id =?",uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<User> selectByUAG(StringBuilder where1, List<String> I)  {
        String sql="select * from tb_user" +where1;
        System.out.println(sql);
        try {
            List<User> users = queryRunner.query(sql, new BeanListHandler<>(User.class), I.toArray());
            return users;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
